<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(item, index) in suggestions"
      :key="index"
      icon="search"
      @click="$emit('search',item)"
    >
    <div v-html="highlight(item)" slot="title"></div>
    </van-cell>
    <!-- {{htmlstr}} -->
    <!-- <div v-html="htmlstr"></div> -->
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
import { debounce } from 'lodash'
export default {
  name: 'SrarchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: []
      // htmlstr:`Hello <span style="color: red">World</span>`
    }
  },
  watch: {
    searchText: {
      /*
  但文本框的内容发生改变的时候就会调用handler这个函数
  这个函数名称是固定的
  */
      /* 防抖 */
      handler: debounce(function (value) {
        this.loadSearchSuggestions(value)
      }, 1000),

      // handler(value) {
      //   // console.log(val);
      //   this.loadSearchSuggestions(value)
      // },
      immediate: true // 侦听开始立即调用~
    }
  },
  methods: {
    // 联想建议
    async loadSearchSuggestions (q) {
      try {
        const { data } = await getSearchSuggestion(q)
        this.suggestions = data.data.options
      } catch {
        this.$toast('获取失败~')
      }
    },
    // 处理高亮
    highlight (item) {
      // 1.先定义要高亮的模板字符串
      const highlightStr = `<span class="active">${this.searchText}</span>`
      // 2.定义要替换的正则表达式
      const reg = new RegExp(this.searchText, 'gi')
      // 3.用suggestiontext替换里面需要高亮的文字
      return item.replace(reg, highlightStr)
      // return item.replace(正则表达式，高亮的文字)
    }
  }
}
</script>

<style scoped lang='less'>
.search-suggestion{
  /deep/ span.active{
    color: red;
  }
}
</style>
